<template>
	<div>
		<van-cell-group inset style="margin-top: 40rpx; margin-bottom: 40rpx;">
			<van-cell title="路由跳转" is-link to="food" />
			<van-cell title="路由跳转" is-link to="food" />
			<van-cell title="路由跳转" is-link to="food" />
		</van-cell-group>
		<van-cell-group inset style="margin-top: 20rpx; margin-bottom: 20rpx;">
			<van-cell v-for="item in cartItems" :key="item.id || item.name" :title="item.name"
				:value="`￥${item.totalPrice}`">
				<template #label>
					数量: {{ item.num }}
				</template>
			</van-cell>
			<van-cell title="帝皇劵" is-link />
			<van-cell title="帝皇卡" is-link />
			<van-field v-model="remark" label="备注" />
		</van-cell-group>
		<van-cell-group inset style="margin-top: 20rpx; margin-bottom: 100rpx;">
			<van-cell title="路由跳转" is-link to="food" />
			<van-cell title="路由跳转" is-link to="food" />
			
		</van-cell-group>
		<van-submit-bar :price="totalPrice*100" button-text="付款" @submit=topay />
		<div style="height: 60rpx;">

		</div>

	</div>
</template>

<script setup>
	import {
		onMounted,
		ref,
		reactive,
		toRefs
	} from 'vue';

	import {
		userStore
	} from '@/store'
	import {
		listAdd
	} from '@/api/store/food.js';

	const userEntity = userStore()
	const cartItems = ref([]);
	const totalPrice = ref(0);

    const remark = ref('')
	const data = reactive({
		form: {},
		goods: [], // 最终的分组数据
	});

	const {
		form,
		goods
	} = toRefs(data);
	//得到总价

	const calculateTotalPrice = () => {
		let sum = 0;
		cartItems.value.forEach(item => {
			sum += item.price * item.num;
		});
		totalPrice.value = sum;
	};

	function loginSuccess(result) {
		// 设置用户信息
		userEntity.GetInfo().then(res => {
			form.value.userName = res.user.userName;
			form.value.userId = res.user.userId;


		})
	}
	

	function topay() {
		
		 const newGoods = data.goods.map(item => ({
		           name: item.name,
		           image: item.image,
		           number: item.num, // 使用 amount 替换 num
		           amount: item.totalPrice
		       }));
		
		const requestData = {
			form: {
				...form.value,
				amount: totalPrice.value,
				remark: remark.value
			},
			goods: newGoods
		};
		console.log(requestData)
		listAdd(requestData).then(response => {
			uni.showToast({
			  title: "支付成功",
			  icon: 'success'
			})
			
			 uni.switchTab({
			   url: `../list/list`,
			});
			
		});
	}

	onMounted(() => {
		const storedCartItems = uni.getStorageSync('cartItems');
		if (storedCartItems) {
			cartItems.value = JSON.parse(storedCartItems);
		}
		calculateTotalPrice();
		loginSuccess();
		goods.value = cartItems.value
		form.value.amount = totalPrice.value
		console.log(totalPrice.value)
		


	});
</script>